﻿using DotNetCore.CAP;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace CAPConsoleDemo
{
    public class Publish : IHostedService
    {
        private ICapPublisher capPublish;  //CAP发布程序
        private Timer _timer;   //定时器

        public Publish(ICapPublisher capPublish)  //自动注入CAP程序
        {
            this.capPublish = capPublish;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(work, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));  //每秒运行一次推送任务
            return Task.CompletedTask;
        }
        private void work(object state)
        {
            capPublish.Publish<string>("Order.Created", DateTime.Now.ToString());  //推送Order.Created事件
            Console.WriteLine("推送：" + DateTime.Now.ToString());
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
